package com.ming_za.odupdaterserver.core.controller.web;

import com.ming_za.odupdaterserver.core.exception.ROEnum;
import com.ming_za.odupdaterserver.core.utils.Msg;
import com.ming_za.odupdaterserver.core.utils.account.AccountManager;
import com.ming_za.odupdaterserver.core.utils.account.param.ReturnAccountPackage;
import com.ming_za.odupdaterserver.core.vo.R;
import com.ming_za.odupdaterserver.core.vo.req.ModifyPasswordVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

@Tag(name = "管理账号API")
@RestController
@RequestMapping("/sev-v/account")
public class AccountManagementAPI {

    private final AccountManager accountManager;

    public AccountManagementAPI(AccountManager accountManager) {
        this.accountManager = accountManager;
    }

    @Operation(summary = "修改密码",description = "首次修改不需要传入旧密码，自动注册单账户")
    @PostMapping("/password")
    public R<?> modifyPassword(HttpServletRequest request, @RequestBody @Valid ModifyPasswordVo modifyPasswordVo){

        if (accountManager.getAllAccount().isEmpty()){
            //首次
            accountManager.registerAccount(modifyPasswordVo.getNewPassword(),null);
            Msg.getInstance().info("&a[" + request.getRemoteHost() + "]首次登录。成功创建密码！");
            return R.ok();
        }else {
            ReturnAccountPackage<Void> voidReturnAccountPackage = accountManager.modifyPassword(modifyPasswordVo.getOldPassword(), modifyPasswordVo.getNewPassword());
            if(voidReturnAccountPackage.isSuccess()){
                Msg.getInstance().warn("&f[" + request.getRemoteHost() + "]修改密码。");
            }
            return R.pack(ROEnum.account(voidReturnAccountPackage.getCode()));
        }
    }
}
